package bounjour.ui;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bounjour.User;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class BaseServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected Configuration cfg; 
	Map<String,Object> map = new HashMap<String,Object>();
	
	protected User getUser(HttpServletRequest request) {
		HttpSession session = request.getSession();
		if (session == null) return null;
		if (session.getAttribute("user") == null) return null;
		return (User)session.getAttribute("user");
	}
	
	
    public void init() {
        cfg = new Configuration();
        cfg.setServletContextForTemplateLoading(getServletContext(), "WEB-INF/templates");
    }
    
    protected void process(HttpServletRequest request, HttpServletResponse response, String templateName)  {
    	process(request, response, templateName, true);
    }
    	
    protected void process(HttpServletRequest request, HttpServletResponse response, String templateName, Boolean loginRequired)  {
    	
		try {
			if (loginRequired && getUser(request) == null) {
	    			response.sendRedirect("Login");
			} else {
				Template t = cfg.getTemplate(templateName);
				response.setContentType("text/html; charset=" + t.getEncoding());
				if (getUser(request) != null) {
					map.put("user", getUser(request).getDisplayName());
				} else {
					map.put("user", "Anonymous");
				}
				if (!map.containsKey("title")) map.put("title", "");
				if (!map.containsKey("message")) map.put("message", "");
				t.process(map, response.getWriter());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
}
